package cn.ccew.sys.web.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ccew.common.base.model.BaseEntity;
import cn.ccew.common.utils.IEntityMapping;
import cn.ccew.sys.model.SysOrgnization;
import cn.ccew.sys.model.SysPersonnel;
import cn.ccew.sys.model.SysRole;
import cn.ccew.sys.web.SysBaseController;

@Controller
public class UserController extends SysBaseController {
	/**
	 * 分页加载
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("user_loadUserList.wb")
	public void loadUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysPersonnel.class);

		String orgId = "";
		if (isParameterExist(request, "orgId")) {
			orgId = request.getParameter("orgId");
			criteria.add(Restrictions.eq("org.id", orgId));
		}

		criteria.addOrder(Order.asc("priority"));
		// String[] excludes = new String[] { "org", "role", "loginPassword",
		// "createTime", "lastModifyTime", "priority" };

		// responseListJSON(criteria, request, response, excludes);

		responseListJSON(criteria, request, response, new PersonnelMapp());
	}

	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("user_savePersonnel.wb")
	public void savePersonnel(@ModelAttribute() SysPersonnel personnel, String pId, String role_name, HttpServletRequest request, HttpServletResponse response) throws Exception {

		try {
			if (StringUtils.isEmpty(personnel.getId())) {
				List<SysPersonnel> list = baseService.findListByProperty("loginName", personnel.getLoginName(), SysPersonnel.class);
				if (list.size() > 0) {
					writerFailure(response, "保存失败,登录名已存在，请重新输入");
					return;
				}
			} else {
				SysPersonnel temp = baseService.findById(personnel.getId(), SysPersonnel.class);
				SysRole role = temp.getRole();
				if (null != role && role.getRoleLayer() == 1) {
					if (!role.getId().equals(role_name)) {
						writerFailure(response, "保存失败,超级管理员的权限不能修改");
						return;
					}
				}
			}
			SysOrgnization org = baseService.findById(pId, SysOrgnization.class);
			personnel.setOrg(org);
			SysRole role = baseService.findById(role_name, SysRole.class);
			personnel.setRole(role);
			baseService.saveOrUpdate(personnel);
			writerSuccess(response, "保存成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}

	/**
	 * 加载一条记录，用于显示修改
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("user_loadPersonnel.wb")
	public void user_loadPersonnel(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysPersonnel p = baseService.findById(id, SysPersonnel.class);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", p.getId());
		map.put("pId", p.getOrg().getId());
		map.put("realName", p.getRealName());
		map.put("loginName", p.getLoginName());
		map.put("loginPassword", p.getLoginPassword());
		map.put("phone", p.getPhone());
		map.put("tel", p.getTel());
		map.put("qq", p.getQq());
		map.put("email", p.getEmail());
		map.put("infoState", p.getInfoState());

		map.put("role_id", null == p.getRole().getId() ? "" : p.getRole().getId());

		responseListJSON(response, map);
	}

	class PersonnelMapp implements IEntityMapping {

		@Override
		public List<Map<String, Object>> excute(List<BaseEntity> list) {
			List<Map<String, Object>> uu = new ArrayList<Map<String, Object>>();
			for (BaseEntity infoBase : list) {
				SysPersonnel info = (SysPersonnel) infoBase;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", info.getId());
				map.put("pId", info.getOrg().getId());
				map.put("realName", info.getRealName());
				map.put("loginName", info.getLoginName());
				map.put("loginPassword", info.getLoginPassword());
				map.put("phone", info.getPhone());
				map.put("tel", info.getTel());
				map.put("qq", info.getQq());
				map.put("email", info.getEmail());
				map.put("infoStateString", info.getInfoStateString());

				map.put("roleName", null == info.getRole() ? "" : info.getRole().getRoleName());

				uu.add(map);
			}
			return uu;
		}
	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("user_removePersonnel.wb")
	public void user_removePersonnel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysPersonnel personnel = null;
		if (isParameterExist(request, "id")) {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				personnel = baseService.findById(id, SysPersonnel.class);
			}
		}
		if (null == personnel) {
			writerFailure(response, "删除失败，没有找个记录");
			return;
		}
		try {
			baseService.delete(personnel.getId(), SysPersonnel.class);
			writerSuccess(response, "删除成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writerFailure(response, "删除失败，未知原因");
		}

	}

	/**
	 * 修改状态
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("user_modifyPersonnelState.wb")
	public void user_modifyPersonnelState(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysPersonnel personnel = null;
		if (isParameterExist(request, "id")) {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				personnel = baseService.findById(id, SysPersonnel.class);
			}
		}
		if (null == personnel) {
			writerFailure(response, "失败，没有找个该记录");
			return;
		}
		if (isParameterExist(request, "state")) {
			String state = request.getParameter("state");
			if (StringUtils.isNotEmpty(state)) {
				try {
					int stateint = Integer.parseInt(state);
					personnel.setInfoState(stateint);
				} catch (Exception e) {
					writerFailure(response, "状态参数不符合");
				}
			}
		}
		try {
			baseService.saveOrUpdate(personnel);
			writerSuccess(response, "操作成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writerFailure(response, "操作失败，保存数据时发生异常");
		}
	}

}
